package com.vslimit.util;

/**
 * Created by IntelliJ IDEA.
 * User: vslimit
 * Date: 12-4-2
 * Time: 下午11:36
 * To change this template use File | Settings | File Templates.
 */

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

/**
 * User: LanJian Date: 2010-01-11
 */
public class StringUtil {

    public static final String LOCATION_AFTER = "after";
    public static final String LOCATION_FRONT = "front";

    //系统使用的编码方式
    public static final String ENCODING_UTF8 = "utf-8";
    public static final String ENCODING_LATIN_ONE = "iso-8859-1";


    public static final String SEPARATOR = ",";

    static int passwordLength;

    public int getPasswordLength() {
        return passwordLength;
    }

    public void setPasswordLength(int passwordLength) {
        StringUtil.passwordLength = passwordLength;
    }


    public static String genPassword() {
        final int maxNum = 26 + 26 + 10;
        int count = 0, i;
        char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
                'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
                'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
                'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6',
                '7', '8', '9'};

        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while (count < passwordLength) {
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }
        return pwd.toString();
    }

    public static String fillLeadingZeros(String oringinal, int minLength) {
        if (oringinal.length() >= minLength)
            return oringinal;

        StringBuffer prefixBuffer = new StringBuffer();
        int m = minLength - oringinal.length();
        for (int i = 0; i < m; i++) {
            prefixBuffer.append("0");
        }
        return prefixBuffer.append(oringinal).toString();

    }

    public static boolean isEmpty(String val) {
        if ((null == val) || ("".equals(val)) || ("null".equals(val))
                || "".equals(val.trim())) {
            return true;
        } else {
            return false;
        }
    }


    public static boolean isEmptyOrZero(String val) {
        if ((null == val) || ("".equals(val)) || ("null".equals(val) || "0".equals(val) || "0-0".equals(val))
                || "".equals(val.trim())) {
            return true;
        } else {
            return false;
        }
    }

    public static String fillStr(int length, char defaultChar) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append(defaultChar);
        }
        return sb.toString();
    }

    public static String replaceString(String target, int index, char re) {
        StringBuffer sb = new StringBuffer();
        if (isEmpty(target)) {
            for (int i = 0; i < 4; i++) {
                if (i == index) {
                    sb.append(re);
                } else {
                    sb.append("0");
                }
            }
        } else {
            char[] charArr = target.toCharArray();
            for (int i = 0; i < charArr.length; i++) {
                if (i == index) {
                    sb.append(re);
                } else {
                    sb.append(charArr[i]);
                }
            }
        }

        return sb.toString();
    }

    public static List split(String str, String splitSign) {
        int index;
        if (str == null || splitSign == null) {
            return null;
        }
        List list = new ArrayList();
        if (!StringUtil.isEmpty(str)) {
            while ((index = str.indexOf(splitSign)) != -1) {
                list.add(str.substring(0, index));
                str = str.substring(index + splitSign.length());
            }
            list.add(str);
        }
        return list;
    }

    public static String splitLast(String str, String splitSign) {
        String splitStr = null;
        if (str == null || splitSign == null) {
            return null;
        }
        if (!StringUtil.isEmpty(str)) {
            splitStr = str.substring(0, str.lastIndexOf(splitSign));
        }
        return splitStr;
    }

    public static String splitStr(String str, String splitSign, String location) {
        String splitStr = null;
        if (str == null || splitSign == null) {
            return null;
        }
        if (!StringUtil.isEmpty(str)) {
            if (str.indexOf(splitSign) != -1) {
                if (StringUtil.LOCATION_FRONT.equals(location)) {
                    splitStr = str.substring(0, str.indexOf(splitSign));
                } else if (StringUtil.LOCATION_AFTER.equals(location)) {
                    splitStr = str.substring(str.indexOf(splitSign) + 1, str.length());
                }
            }
        }
        return splitStr;
    }

    public static Long operateNumber(Long num, Long _num, String operateCode) {
        if (isEmpty(operateCode)) {
            return 0l;
        } else {
            if ("+".equals(operateCode)) {
                return num + _num;
            } else if ("+".equals(operateCode)) {
                return num + _num;
            } else {
                return 0l;
            }
        }
    }

    public static Integer transToInt(String str, Integer defaultValue) {
        return isEmpty(str) ? defaultValue : Integer.valueOf(str);
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return !isEmpty(str) && pattern.matcher(str).matches();
    }

    public static boolean isConnect(Object value) {
        if (value != null) {
            String tempStr = value.toString();
            if (!isEmpty(tempStr)) {
                return true;
            } else if (!"0".equals(tempStr)) {
                return true;
            }
        }
        return false;
    }

    public static String subString(String str, Integer number) {
        return (isEmpty(str) || str.length() < number) ? str : str.substring(0, number);
    }

    public static String strip(String html) {
        if (!isEmpty(html)) {
            html = html.replaceAll("\n", "");
            html = html.replaceAll("<xml>.*</xml>", "");
            html = html.replaceAll("<script[^>]*>(?:\\s|\\S)*?</script>", "");
            html = html.replaceAll("<style[^>]*>(?:\\s|\\S)*?</style>", "");
            //html = html.replaceAll("(<(?!/?(?i)(em)).*?>)|([^<]+/>)", ""); //"<[^<>]+>" <(.*)>.*<\/>|<(.*) \/>       "<[^<>]+/?>?\\s?"
            html = html.replaceAll("<[^<>]+/?>", "");
            html = html.replaceAll("&?[a-z]+;", "");
            html = html.replaceAll("funi365_pagination;", "");
            html = html.replaceAll("funi365_;", "");
            html = html.replaceAll("funi365_", "");
        }

        return html;
    }

    public static void main(String[] ages) {
        String aaa = "128478.1415798846";
        BigDecimal a = new BigDecimal(aaa);
        Integer b = 123;
        System.out.println(loadPointBigDecimal(a, 0));
        System.out.println(isBigDecimal(a));
        System.out.println(isBigDecimal(b));


    }

    public static BigDecimal loadPointBigDecimal(BigDecimal val, Integer number) {
        return val.setScale((null == number || number < 0) ? 0 : number, BigDecimal.ROUND_HALF_UP);
    }


    private static Integer YUAN_TO_FEN_RATIO = 100;
    private static final Double FIX_FLOAT_ERR_NUMBER = 0.000001;

    public static String convertChinese(double money) {
        char[] s1 = {'零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'};
        char[] s4 = {'分', '角', '元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟', '万'};
        String str = String.valueOf(Math.round(money * YUAN_TO_FEN_RATIO + FIX_FLOAT_ERR_NUMBER));
        String result = "";

        for (int i = 0; i < str.length(); i++) {
            int n = str.charAt(str.length() - 1 - i) - '0';
            result = s1[n] + "" + s4[i] + result;
        }

        result = result.replaceAll("零仟", "零");
        result = result.replaceAll("零佰", "零");
        result = result.replaceAll("零拾", "零");
        result = result.replaceAll("零亿", "亿");
        result = result.replaceAll("零万", "万");
        result = result.replaceAll("零元", "元");
        result = result.replaceAll("零角", "零");
        result = result.replaceAll("零分", "零");

        result = result.replaceAll("零零", "零");
        result = result.replaceAll("零亿", "亿");
        result = result.replaceAll("零零", "零");
        result = result.replaceAll("零万", "万");
        result = result.replaceAll("零零", "零");
        result = result.replaceAll("零元", "元");
        result = result.replaceAll("亿万", "亿");

        result = result.replaceAll("零$", "");
        result = result.replaceAll("元$", "元整");
        return result;
    }

    public static boolean containsInArray(String s, String[] sArr) {
        for (String ts : sArr) {
            if (s.equals(ts)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isBigDecimal(Object object) {
        return object instanceof BigDecimal;
    }

    public static boolean isChinese(String str) {
        return str.getBytes().length != str.length();
    }

    public static HashMap<String, String> parseTokenString(String request_token) {
        HashMap<String, String> tokens = new HashMap<String, String>();
        request_token += "&";
        while (request_token.length() > 0) {
            String key_value = request_token.substring(0, request_token.indexOf("&"));
            String key = key_value.substring(0, key_value.indexOf("="));
            String value = key_value.substring(key_value.indexOf("=") + 1, key_value.length());
            tokens.put(key, value);
            request_token = request_token.substring(request_token.indexOf("&") + 1, request_token.length());
        }
        return tokens;
    }

    /**
     * 检验 ListFiled （如a,b,c,d） 是否包含某值
     *
     * @param search
     * @param target
     * @return
     */
    public static boolean isContainsInListField(String search, String target) {
        return !isEmpty(target) && !isEmpty(search) && target.contains(search);
    }

    /**
     * 将指定值 加入到ListFiled中
     *
     * @param value
     * @param target
     * @return
     */
    public static String pushToListFiled(String value, String target) {
        if (isContainsInListField(value, target)) {
            return target;
        }
        List list = split(target, SEPARATOR);
        list = list == null ? new ArrayList() : list;
        list.add(value);
        return arrayToString(list.toArray());
    }

    /**
     * 将Array 转化为字符如(a,b,c,d)
     *
     * @return
     */
    public static String arrayToString(Object[] array) {
        try {
            StringBuffer sb = new StringBuffer();
            for (Object string : array) {
                sb.append(string.toString() + SEPARATOR);
            }
            return sb.substring(0, sb.length() - 1);
        } catch (NullPointerException e) {
            throw new NullPointerException(e.getMessage());
        }
    }

}

